<script setup>
import { ref } from 'vue'
import {
  articleUpdataService,
  articleAddService
} from '@/api/article.js'
const dialogFormVisible = ref()
const list = ref()
const isEdit = ref(true)
const open = (obj) => {
  dialogFormVisible.value = true
  list.value = obj
  isEdit.value = list.value.id ? true : false
  formModel.value = { ...obj }
}

const formModel = ref({
  cate_name: '',
  cate_alias: ''
})
const rule = {
  cate_name: [
    {
      required: true,
      message: '请输入分类名',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    {
      pattern: /^[a-zA-Z0-9]{1,5}$/,
      message: '别名为1——5位字母和数字',
      trigger: 'blur'
    },
    {
      required: true,
      message: '请输入分类名',
      trigger: 'blur'
    }
  ]
}

const formRef = ref()
const emit = defineEmits(['updata'])
const sub = async () => {
  await formRef.value.validate()
  isEdit.value
    ? await articleUpdataService(formModel.value)
    : await articleAddService(formModel.value)
  isEdit.value
    ? ElMessage.success('更新成功')
    : ElMessage.success('成功添加')
  emit('updata')
  dialogFormVisible.value = false
}

defineExpose({
  open
})
</script>
<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="isEdit ? '编辑分类' : '添加分类'"
    width="500"
  >
    <el-form
      :model="formModel"
      :rules="rule"
      ref="formRef"
    >
      <el-form-item
        label="分类名称"
        prop="cate_name"
      >
        <el-input v-model="formModel.cate_name" />
      </el-form-item>
      <el-form-item
        label="分类别名"
        prop="cate_alias"
      >
        <el-input
          v-model="formModel.cate_alias"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          @click="dialogFormVisible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="sub">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
